package co.yixiang.modules.shop.service.impl;

import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import co.yixiang.exception.BadRequestException;
import co.yixiang.modules.shop.domain.*;
import co.yixiang.modules.shop.repository.*;
import co.yixiang.modules.shop.service.YxStoreCategoryService;
import co.yixiang.modules.shop.service.YxStoreProductService;
import co.yixiang.modules.shop.service.dto.*;
import co.yixiang.modules.shop.service.mapper.YxStoreProductMapper;
import co.yixiang.utils.*;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author hupeng
 * @date 2019-10-04
 */
@Service
@Transactional(propagation = Propagation.SUPPORTS, readOnly = true, rollbackFor = Exception.class)
public class YxStoreProductServiceImpl implements YxStoreProductService {

    private final YxStoreProductRepository yxStoreProductRepository;
    private final YxStoreProductAttrRepository yxStoreProductAttrRepository;
    private final YxStoreProductAttrValueRepository yxStoreProductAttrValueRepository;
    private final YxStoreProductAttrResultRepository yxStoreProductAttrResultRepository;
    private final YxStoreCategoryService yxStoreCategoryService;

    private final YxStoreProductMapper yxStoreProductMapper;

    private final YxStoreProductLockRepository yxStoreProductLockRepository;


    public YxStoreProductServiceImpl(YxStoreProductRepository yxStoreProductRepository,
                                     YxStoreProductAttrRepository yxStoreProductAttrRepository, YxStoreProductAttrValueRepository yxStoreProductAttrValueRepository,
                                     YxStoreProductAttrResultRepository yxStoreProductAttrResultRepository, YxStoreCategoryService yxStoreCategoryService, YxStoreProductMapper yxStoreProductMapper, YxStoreProductLockRepository yxStoreProductLockRepository) {
        this.yxStoreProductRepository = yxStoreProductRepository;
        this.yxStoreProductAttrRepository = yxStoreProductAttrRepository;
        this.yxStoreProductAttrValueRepository = yxStoreProductAttrValueRepository;
        this.yxStoreProductAttrResultRepository = yxStoreProductAttrResultRepository;
        this.yxStoreCategoryService = yxStoreCategoryService;
        this.yxStoreProductMapper = yxStoreProductMapper;
        this.yxStoreProductLockRepository = yxStoreProductLockRepository;
    }

    @Override
    public Map<String, Object> queryAll(YxStoreProductQueryCriteria criteria, Pageable pageable) {
        //根据商品分类ID切换
        if (criteria.getCateId() != null && criteria.getCateId() != -1) {
            Set<YxStoreCategory> set = new LinkedHashSet<>();
            YxStoreCategory yxStoreCategory = new YxStoreCategory();
            //父级id
            yxStoreCategory.setId(criteria.getCateId());
            set.add(yxStoreCategory);
            //根据商品分类ID查询所有子集ID
            List<Map<String, Integer>> listMap = yxStoreCategoryService.findByChildCategory(criteria.getCateId());
            for (Map<String, Integer> mapData : listMap) {
                //拼装所有子集的分类ID
                if (mapData.get("id") != null) {
                    YxStoreCategory storeCategory = new YxStoreCategory();
                    storeCategory.setId(mapData.get("id"));
                    set.add(storeCategory);
                }
                if (mapData.get("pid") != null) {
                    YxStoreCategory category = new YxStoreCategory();
                    category.setId(mapData.get("pid"));
                    set.add(category);
                }
            }
            criteria.setStoreCategory(set);
        }
        //查询条件在QueryHelp类中的IMAGE_NOT_NULL中定义
        if (criteria.getQueryImage() != null && 0 == criteria.getQueryImage()) {
            ///查询不含图片的商品
            criteria.setImage("no");
        } else if (criteria.getQueryImage() != null && 1 == criteria.getQueryImage()) {
            //查询包含图片的商品
            criteria.setImage("yes");
        }
        Page<YxStoreProduct> page = yxStoreProductRepository
                .findAll((root, criteriaQuery, criteriaBuilder)
                                -> QueryHelp.getPredicate(root, criteria, criteriaBuilder)
                        , pageable);

        List<YxStoreProductDTO> storeProductDTOS = new ArrayList<>();
        for (YxStoreProduct product : page.getContent()) {

            YxStoreProductDTO yxStoreProductDTO = yxStoreProductMapper.toDto(product);

            //规格属性库存
//            Integer newStock = yxStoreProductAttrValueRepository.sumStock(product.getId());
//            if (newStock != null) yxStoreProductDTO.setStock(newStock);
            //查询认购商品库规则属性值
            if (StringUtils.isNotEmpty(product.getInvestAttrUnique())) {
                YxStoreProductAttrValue productAttrValue = yxStoreProductAttrValueRepository.findByUnique(product.getInvestAttrUnique());
                yxStoreProductDTO.setProductAttrValue(productAttrValue);
            }
            yxStoreProductDTO.setEditFlag(false);
            //暂不使用
//            List<YxStoreProductAttrValue> listAttr=yxStoreProductAttrValueRepository.findByProductId(product.getId());
//            if(listAttr.size()>1){
//                List<YxStoreProductChildren> listChildren=new ArrayList<>();
//                for (YxStoreProductAttrValue attr:listAttr) {
//                    YxStoreProductChildren children=new YxStoreProductChildren();
//                    //零售价
//                    children.setPrice(attr.getPrice());
//                    //进货价
//                    children.setCost(attr.getPleased());
//                    //成本价
//                    children.setInvestCost(attr.getCost());
//                    //库存
//                    children.setStock(attr.getStock());
//                    listChildren.add(children);
//                }
//                yxStoreProductDTO.setChildren(listChildren);
//            }
            storeProductDTOS.add(yxStoreProductDTO);
        }
        Map<String, Object> map = new LinkedHashMap<>(2);
        map.put("content", storeProductDTOS);
        map.put("totalElements", page.getTotalElements());
        return map;
    }

    @Override
    public List<YxStoreProductDTO> queryAll(YxStoreProductQueryCriteria criteria) {
        return yxStoreProductMapper.toDto(yxStoreProductRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root, criteria, criteriaBuilder)));
    }

    @Override
    public YxStoreProductDTO findById(Integer id) {
        YxStoreProductDTO dto = null;
        Optional<YxStoreProduct> yxStoreProduct = yxStoreProductRepository.findById(id);
        ValidationUtil.isNull(yxStoreProduct, "YxStoreProduct", "id", id);
        if (yxStoreProduct.isPresent()) {
            dto = yxStoreProductMapper.toDto(yxStoreProduct.get());
        }
        return dto;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public YxStoreProductDTO create(YxStoreProduct resources) {
        if (resources.getIsMallOn() == null) {
            resources.setIsMallOn(0);
        }
        resources.setAddTime(OrderUtil.getSecondTimestampTwo());
        resources.setAdder(SecurityUtils.getUsername());
        return yxStoreProductMapper.toDto(yxStoreProductRepository.save(resources));
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void update(YxStoreProduct resources) {
        Optional<YxStoreProduct> optionalYxStoreProduct = yxStoreProductRepository.findById(resources.getId());
        Integer stock = optionalYxStoreProduct.get().getStock() != null ? optionalYxStoreProduct.get().getStock() : 0;
        ValidationUtil.isNull(optionalYxStoreProduct, "YxStoreProduct", "id", resources.getId());
        YxStoreProduct yxStoreProduct = optionalYxStoreProduct.get();
        yxStoreProduct.copy(resources);
        yxStoreProductRepository.save(yxStoreProduct);
        if (resources.getStock() != null) {
            //修改商品属性
            YxStoreProductAttrResult yxStoreProductAttrResult = yxStoreProductAttrResultRepository
                    .findByProductId(resources.getId());
            //修改库存， 同时修改yx_store_product和属性表的库存
            if (ObjectUtil.isNotNull(yxStoreProductAttrResult) && !stock.equals(resources.getStock())) {
                Integer id = resources.getId();
                String jsonStr = yxStoreProductAttrResult.getResult();
                JSONObject jsonObject = JSON.parseObject(jsonStr);

                List<ProductFormatDTO> valueList = JSON.parseArray(
                        jsonObject.get("value").toString(), ProductFormatDTO.class);
                if (valueList != null && valueList.size() > 0) {
                    List<YxStoreProductAttrValue> valueGroup = new ArrayList<>();
                    List<ProductFormatDTO> newListFormatDTO = new ArrayList<>();
                    for (ProductFormatDTO productFormatDTO : valueList) {
                        YxStoreProductAttrValue yxStoreProductAttrValue = new YxStoreProductAttrValue();
                        yxStoreProductAttrValue.setProductId(id);
                        //productFormatDTO.getDetail().values().stream().collect(Collectors.toList());
                        List<String> stringList = productFormatDTO.getDetail().values()
                                .stream().collect(Collectors.toList());
                        Collections.sort(stringList);
                        yxStoreProductAttrValue.setSuk(StrUtil.
                                join(",", stringList));
                        yxStoreProductAttrValue.setPrice(BigDecimal.valueOf(productFormatDTO.getPrice() != null ? productFormatDTO.getPrice() : 0));
                        yxStoreProductAttrValue.setCost(BigDecimal.valueOf(productFormatDTO.getCost() != null ? productFormatDTO.getCost() : 0));
                        //重新调整库存
                        yxStoreProductAttrValue.setStock(yxStoreProduct.getStock());
                        yxStoreProductAttrValue.setUnique(IdUtil.simpleUUID());
                        yxStoreProductAttrValue.setImage(productFormatDTO.getPic());
                        yxStoreProductAttrValue.setBarCode(productFormatDTO.getBarCode());
                        yxStoreProductAttrValue.setPleased(BigDecimal.valueOf(productFormatDTO.getPleased() != null ? productFormatDTO.getPleased() : 0));

                        valueGroup.add(yxStoreProductAttrValue);

                        //重新调整库存
                        productFormatDTO.setSales(yxStoreProduct.getStock());
                        newListFormatDTO.add(productFormatDTO);
                    }
                    //插入之前清空
                    yxStoreProductAttrValueRepository.deleteByProductId(id);
                    //保存值
                    yxStoreProductAttrValueRepository.saveAll(valueGroup);


                    Map<String, Object> map = new LinkedHashMap<>();
                    map.put("attr", jsonObject.get("attr"));
                    map.put("value", newListFormatDTO);

                    //保存结果
                    setResult(map, id);
                }
            }
        }

    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void delete(Integer id) {
        yxStoreProductRepository.updateDel(1, id);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void recovery(Integer id) {
        yxStoreProductRepository.updateDel(0, id);
        yxStoreProductRepository.updateOnsale(0, id);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void onSale(Integer id, Integer status) {
        if (status == 1) {
            status = 0;
        } else {
            status = 1;
        }
        yxStoreProductRepository.updateOnsale(status, id);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public List<ProductFormatDTO> isFormatAttr(Integer id, String jsonStr) {
        if (ObjectUtil.isNull(id)) throw new BadRequestException("产品不存在");

        YxStoreProductDTO yxStoreProductDTO = findById(id);

        DetailDTO detailDTO = attrFormat(jsonStr);

        //System.out.println("list:"+detailDTO.getRes());
        List<ProductFormatDTO> newList = new ArrayList<>();
        for (Map<String, Map<String, String>> map : detailDTO.getRes()) {
            ProductFormatDTO productFormatDTO = new ProductFormatDTO();

            productFormatDTO.setDetail(map.get("detail"));
            productFormatDTO.setCost(yxStoreProductDTO.getCost()!=null?yxStoreProductDTO.getCost().doubleValue():0);
            productFormatDTO.setPrice(yxStoreProductDTO.getPrice()!=null?yxStoreProductDTO.getPrice().doubleValue():0);
            productFormatDTO.setSales(yxStoreProductDTO.getSales());
            productFormatDTO.setPic(yxStoreProductDTO.getImage());
            productFormatDTO.setPleased(yxStoreProductDTO.getInvestCost()!=null?yxStoreProductDTO.getInvestCost().doubleValue():0);
            productFormatDTO.setBarCode(yxStoreProductDTO.getBarCode());
            productFormatDTO.setSalesReference(yxStoreProductDTO.getSalesReference());
            productFormatDTO.setPromotePrice(yxStoreProductDTO.getPromotePrice()!=null?yxStoreProductDTO.getPromotePrice().doubleValue():0);
            productFormatDTO.setCheck(false);
            newList.add(productFormatDTO);

        }


        return newList;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void createProductAttr(Integer id, String jsonStr) {
        JSONObject jsonObject = JSON.parseObject(jsonStr);
        //System.out.println(jsonObject);
        List<FromatDetailDTO> attrList = JSON.parseArray(
                jsonObject.get("items").toString(),
                FromatDetailDTO.class);
        List<ProductFormatDTO> valueList = JSON.parseArray(
                jsonObject.get("attrs").toString(),
                ProductFormatDTO.class);


        List<YxStoreProductAttr> attrGroup = new ArrayList<>();
        for (FromatDetailDTO fromatDetailDTO : attrList) {
            YxStoreProductAttr yxStoreProductAttr = new YxStoreProductAttr();
            yxStoreProductAttr.setProductId(id);
            yxStoreProductAttr.setAttrName(fromatDetailDTO.getValue());
            yxStoreProductAttr.setAttrValues(StrUtil.
                    join(",", fromatDetailDTO.getDetail()));
            attrGroup.add(yxStoreProductAttr);
        }


        List<YxStoreProductAttrValue> valueGroup = new ArrayList<>();
        for (ProductFormatDTO productFormatDTO : valueList) {
            YxStoreProductAttrValue yxStoreProductAttrValue = new YxStoreProductAttrValue();
            yxStoreProductAttrValue.setProductId(id);
            //productFormatDTO.getDetail().values().stream().collect(Collectors.toList());
            List<String> stringList = productFormatDTO.getDetail().values()
                    .stream().collect(Collectors.toList());
            Collections.sort(stringList);
            yxStoreProductAttrValue.setSuk(StrUtil.
                    join(",", stringList));
            yxStoreProductAttrValue.setPrice(BigDecimal.valueOf(productFormatDTO.getPrice()));
            yxStoreProductAttrValue.setCost(BigDecimal.valueOf(productFormatDTO.getCost()));
            yxStoreProductAttrValue.setStock(productFormatDTO.getSales());
            yxStoreProductAttrValue.setUnique(IdUtil.simpleUUID());
            yxStoreProductAttrValue.setImage(productFormatDTO.getPic());
            yxStoreProductAttrValue.setBarCode(productFormatDTO.getBarCode());
            yxStoreProductAttrValue.setPleased(BigDecimal.valueOf(productFormatDTO.getPleased()));
            yxStoreProductAttrValue.setPromotePrice(BigDecimal.valueOf(productFormatDTO.getPromotePrice()));
            valueGroup.add(yxStoreProductAttrValue);
        }

        if (attrGroup.isEmpty() || valueGroup.isEmpty()) {
            throw new BadRequestException("请设置至少一个属性!");
        }

        //插入之前清空
        clearProductAttr(id, false);


        //保存属性
        yxStoreProductAttrRepository.saveAll(attrGroup);

        //保存值
        yxStoreProductAttrValueRepository.saveAll(valueGroup);

        Map<String, Object> map = new LinkedHashMap<>();
        map.put("attr", jsonObject.get("items"));
        map.put("value", jsonObject.get("attrs"));

        //保存结果
        setResult(map, id);

    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void setResult(Map<String, Object> map, Integer id) {
        YxStoreProductAttrResult yxStoreProductAttrResult = new YxStoreProductAttrResult();
        yxStoreProductAttrResult.setProductId(id);
        yxStoreProductAttrResult.setResult(JSON.toJSONString(map));
        yxStoreProductAttrResult.setChangeTime(OrderUtil.getSecondTimestampTwo());

        yxStoreProductAttrResultRepository.deleteByProductId(id);

        yxStoreProductAttrResultRepository.save(yxStoreProductAttrResult);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void clearProductAttr(Integer id, boolean isActice) {
        if (ObjectUtil.isNull(id)) throw new BadRequestException("产品不存在");

        yxStoreProductAttrRepository.deleteByProductId(id);
        yxStoreProductAttrValueRepository.deleteByProductId(id);

        if (isActice) {
            yxStoreProductAttrResultRepository.deleteByProductId(id);
        }
    }

    @Override
    public String getStoreProductAttrResult(Integer id) {
        YxStoreProductAttrResult yxStoreProductAttrResult = yxStoreProductAttrResultRepository
                .findByProductId(id);
        if (ObjectUtil.isNull(yxStoreProductAttrResult)) return "";
        return yxStoreProductAttrResult.getResult();
    }

    /**
     * 组合规则属性算法
     *
     * @param jsonStr
     * @return
     */
    public DetailDTO attrFormat(String jsonStr) {
        // List<Object> returnList = new ArrayList<>();

        JSONObject jsonObject = JSON.parseObject(jsonStr);
        List<FromatDetailDTO> fromatDetailDTOList = JSON.parseArray(jsonObject.get("items").toString(),
                FromatDetailDTO.class);
        List<String> data = new ArrayList<>();
        //List<Map<String,List<Map<String,String>>>> res =new ArrayList<>();
        List<Map<String, Map<String, String>>> res = new ArrayList<>();

        if (fromatDetailDTOList.size() > 1) {
            for (int i = 0; i < fromatDetailDTOList.size() - 1; i++) {
                if (i == 0) data = fromatDetailDTOList.get(i).getDetail();
                List<String> tmp = new LinkedList<>();
                for (String v : data) {
                    for (String g : fromatDetailDTOList.get(i + 1).getDetail()) {
                        String rep2 = "";
                        if (i == 0) {
                            rep2 = fromatDetailDTOList.get(i).getValue() + "_" + v + "-"
                                    + fromatDetailDTOList.get(i + 1).getValue() + "_" + g;
                        } else {
                            rep2 = v + "-"
                                    + fromatDetailDTOList.get(i + 1).getValue() + "_" + g;
                        }

                        tmp.add(rep2);

                        if (i == fromatDetailDTOList.size() - 2) {
                            // Map<String,List<Map<String,String>>> rep4 = new LinkedHashMap<>();
                            Map<String, Map<String, String>> rep4 = new LinkedHashMap<>();
                            //List<Map<String,String>> listMap = new ArrayList<>();
                            //Map<String,String> map1 = new LinkedHashMap<>();
                            Map<String, String> reptemp = new LinkedHashMap<>();
                            for (String h : Arrays.asList(rep2.split("-"))) {
                                List<String> rep3 = Arrays.asList(h.split("_"));

                                if (rep3.size() > 1) {
                                    reptemp.put(rep3.get(0), rep3.get(1));
                                } else {
                                    reptemp.put(rep3.get(0), "");
                                }
                                //listMap.add(reptemp);

                            }
                            rep4.put("detail", reptemp);

                            //rep4.put("detail",listMap);

                            res.add(rep4);
                        }
                    }

                }

                //System.out.println("tmp:"+tmp);
                if (!tmp.isEmpty()) {
                    data = tmp;
                }
            }
        } else {
            List<String> dataArr = new ArrayList<>();

            for (FromatDetailDTO fromatDetailDTO : fromatDetailDTOList) {

                for (String str : fromatDetailDTO.getDetail()) {
                    Map<String, Map<String, String>> map2 = new LinkedHashMap<>();
                    //List<Map<String,String>> list1 = new ArrayList<>();
                    dataArr.add(fromatDetailDTO.getValue() + "_" + str);
                    Map<String, String> map1 = new LinkedHashMap<>();
                    map1.put(fromatDetailDTO.getValue(), str);
                    //list1.add(map1);
                    map2.put("detail", map1);
                    res.add(map2);
                }
            }

            String s = StrUtil.join("-", dataArr);
            data.add(s);
        }


        DetailDTO detailDTO = new DetailDTO();
        detailDTO.setData(data);
        detailDTO.setRes(res);


        return detailDTO;
    }

    /**
     * 查询成本价为空或为0的商品
     *
     * @return
     */
    @Override
    public List<YxStoreProduct> findAllPriceNull() {
        return yxStoreProductRepository.findAllPriceNull();
    }

    /**
     * 根据多个id查询商品
     *
     * @param id
     * @return
     */
    @Override
    public List<YxStoreProduct> findArryById(String id) {
        return yxStoreProductRepository.findArryById(id);
    }

    /**
     * 添加或取消投资商品库状态
     *
     * @param id
     * @param isStockInvest
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void onSaleInvest(Integer id, int isStockInvest) {
        int isInvestOn = 0;
        if (isStockInvest == 1) {
            isStockInvest = 0;
        } else {
            isInvestOn = 1;
            isStockInvest = 1;
        }
        yxStoreProductRepository.updateonSaleInvest(isStockInvest, id, isInvestOn);
    }

    /**
     * 保存商品的属性与商品的属性值
     *
     * @param storeProductAttr
     * @param yxStoreProductAttrValue
     */
    @Override
    public void saveProductAttr(YxStoreProductAttr storeProductAttr, YxStoreProductAttrValue yxStoreProductAttrValue) {
        //保存属性
        yxStoreProductAttrRepository.save(storeProductAttr);

        //保存值
        yxStoreProductAttrValueRepository.save(yxStoreProductAttrValue);

    }

    /**
     * 通过商品ID查询规则属性值
     *
     * @param productId
     * @return
     */
    @Override
    public List<YxStoreProductAttrValue> getListProductAttrValue(Integer productId) {
        List<YxStoreProductAttrValue> list = yxStoreProductAttrValueRepository.findByProductId(productId);
        return list;
    }

    /**
     * 查询保留商品管理
     *
     * @param criteria
     * @param pageable
     * @return
     */
    @Override
    public Map<String, Object> findListKeepGoods(KeepGoodsQueryCriteria criteria, Pageable pageable) {
        Page<YxStoreProduct> page = yxStoreProductRepository
                .findAll((root, criteriaQuery, criteriaBuilder)
                                -> QueryHelp.getPredicate(root, criteria, criteriaBuilder)
                        , pageable);
        return PageUtil.toPage(page.map(yxStoreProductMapper::toDto));
    }

    /**
     * 释放保留商品
     *
     * @param id
     * @param lockStatus
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int updateLockStatus(String id, int lockStatus) {
        yxStoreProductLockRepository.updateReleaser(id, "系统");
        return yxStoreProductRepository.updateLockStatus(id, lockStatus);
    }

    /**
     * 查询到期锁定的商品
     *
     * @return
     */
    @Override
    public List<YxStoreProduct> findGoodsLock() {
        return yxStoreProductRepository.findGoodsLock();
    }

    /**
     * 通过品牌名称查询品牌ID
     *
     * @param brandName
     * @return
     */
    @Override
    public Integer findBrandId(String brandName) {
        return yxStoreProductRepository.findBrandId(brandName);
    }

    @Override
    public Integer findDetailId(String name, String label) {
        return yxStoreProductRepository.findDetailId(name, label);
    }

    /**
     * 通过商品名,供应商,门店查询商品
     *
     * @param storeId      门店ID
     * @param storeName    商品名称
     * @param supplierCode 供应商编码
     * @return
     */
    @Override
    public YxStoreProduct findByGoods(String storeId, String storeName, String supplierCode) {
        return yxStoreProductRepository.findByGoods(storeId, storeName, supplierCode);
    }

    /**
     * 根据条码查询商品
     *
     * @param pageable
     * @return
     */
    @Override
    public List<YxStoreProduct> findByBarCode(String pageable) {
        return yxStoreProductRepository.findByBarCode(pageable);
    }

    /**
     * 商城商品上架/下架
     *
     * @param id
     * @param isMallOn
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void onMallSale(Integer id, Integer isMallOn) {
        if (isMallOn == 1) {
            isMallOn = 0;
        } else {
            isMallOn = 1;
        }
        yxStoreProductRepository.updateOnMallSale(isMallOn, id);
    }

    /**
     * 通过商品名,门店查询商品
     *
     * @param storeId   门店ID
     * @param storeName 商品名称
     * @return
     */
    @Override
    public YxStoreProduct findByStoreGoods(String storeId, String storeName) {
        return yxStoreProductRepository.findByStoreGoods(storeId, storeName);
    }

    /**
     * 查询分页库存盘点
     *
     * @param criteria
     * @param pageable
     * @return
     */
    @Override
    public Map<String, Object> getStockTaking(StockTakingQueryCriteria criteria, Pageable pageable) {
        Page<Map> page = yxStoreProductRepository.getStockTaking(criteria.getBeginTime(), criteria.getEndTime(), pageable);
        Map<String, Object> map = new LinkedHashMap<>(2);
        List<Map> listMap = page.getContent();
        List<Map<String, Object>> listDat = new ArrayList<>();
        for (Map mapData : listMap) {
            Map<String, Object> mapObj = new LinkedHashMap<>();
            mapObj.put("storeName", mapData.get("storeName").toString());
            List<YxStoreProductAttrValue> listAttrValue = getListProductAttrValue(Integer.parseInt(mapData.get("id").toString()));
            String suk = listAttrValue != null && listAttrValue.size() > 0 ? listAttrValue.get(0).getSuk() : "";
            mapObj.put("suk", suk);
            mapObj.put("unitName", mapData.get("unitName") != null ? mapData.get("unitName").toString() : "");
            mapObj.put("investCost", mapData.get("investCost") != null ? mapData.get("investCost").toString() : "");
            mapObj.put("stock", mapData.get("stock") != null ? mapData.get("stock").toString() : "");
            mapObj.put("shelfNum", mapData.get("shelfNum") != null ? mapData.get("shelfNum").toString() : "");
            mapObj.put("checkStock", mapData.get("checkStock") != null ? mapData.get("checkStock").toString() : "");
            mapObj.put("differeNumber", mapData.get("differeNumber") != null ? mapData.get("differeNumber").toString() : "");
            mapObj.put("differeAmount", mapData.get("differeAmount") != null ? mapData.get("differeAmount").toString() : "");
            mapObj.put("adder", mapData.get("adder") != null ? mapData.get("adder").toString() : "");
            mapObj.put("checkPeople", mapData.get("checkPeople") != null ? mapData.get("checkPeople").toString() : "");
            mapObj.put("offerorSmoke", mapData.get("offerorSmoke") != null ? mapData.get("offerorSmoke").toString() : "");
            mapObj.put("addTime", mapData.get("addTime") != null ? OrderUtil.stringToDate(mapData.get("addTime").toString()) : "");
            mapObj.put("yxAddTime", mapData.get("yxAddTime") != null ? mapData.get("yxAddTime") : "");
            listDat.add(mapObj);
        }
        map.put("content", listDat);
        map.put("totalElements", page.getTotalElements());
        return map;
    }

    /**
     * 查询不分页库存盘点
     *
     * @param criteria
     * @return
     */
    @Override
    public List<Map<String, Object>> stockTakingList(StockTakingQueryCriteria criteria) {
        return yxStoreProductRepository.stockTakingList(criteria.getBeginTime(), criteria.getEndTime());
    }

    /**
     * 查询已认购的商品
     *
     * @return
     */
    @Override
    public List<Map<String, Objects>> findGoodsSubscript(String storeName, String isInvested, String isHot) {
        return yxStoreProductRepository.findGoodsSubscript(storeName, isInvested, isHot);
    }

    /**
     * 更新认购商品并更新规则属性值
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateSubscripGoods(YxStoreProductDTO yxStoreProductDTO) {
        YxStoreProduct yxStoreProduct = yxStoreProductMapper.toEntity(yxStoreProductDTO);
        yxStoreProductRepository.save(yxStoreProduct);
        //获取商品属性
        YxStoreProductAttrResult yxStoreProductAttrResult = yxStoreProductAttrResultRepository
                .findByProductId(yxStoreProduct.getId());
        // 更新规则属性表
        if (ObjectUtil.isNotNull(yxStoreProductAttrResult)) {
            Integer id = yxStoreProduct.getId();
            String jsonStr = yxStoreProductAttrResult.getResult();
            JSONObject jsonObject = JSON.parseObject(jsonStr);

            List<ProductFormatDTO> valueList = JSON.parseArray(
                    jsonObject.get("value").toString(), ProductFormatDTO.class);
            if (valueList != null && valueList.size() > 0) {
                List<YxStoreProductAttrValue> valueGroup = new ArrayList<>();
                List<ProductFormatDTO> newListFormatDTO = new ArrayList<>();
                for (ProductFormatDTO productFormatDTO : valueList) {
                    YxStoreProductAttrValue yxStoreProductAttrValue = new YxStoreProductAttrValue();
                    yxStoreProductAttrValue.setProductId(id);
                    //productFormatDTO.getDetail().values().stream().collect(Collectors.toList());
                    List<String> stringList = productFormatDTO.getDetail().values()
                            .stream().collect(Collectors.toList());
                    Collections.sort(stringList);
                    yxStoreProductAttrValue.setSuk(StrUtil.
                            join(",", stringList));
                    yxStoreProductAttrValue.setPrice(yxStoreProduct.getPrice());
                    yxStoreProductAttrValue.setCost(yxStoreProduct.getPurchasePrice());
                    //重新调整库存
                    yxStoreProductAttrValue.setStock(yxStoreProduct.getStock());
                    yxStoreProductAttrValue.setUnique(IdUtil.simpleUUID());
                    yxStoreProductAttrValue.setImage(productFormatDTO.getPic());
                    yxStoreProductAttrValue.setBarCode(yxStoreProduct.getBarCode());
                    yxStoreProductAttrValue.setPleased(yxStoreProduct.getCost());

                    valueGroup.add(yxStoreProductAttrValue);

                    //重新调整规则属性
                    productFormatDTO.setSales(yxStoreProduct.getStock());
                    productFormatDTO.setPrice(yxStoreProduct.getPrice().doubleValue());
                    productFormatDTO.setCost(yxStoreProduct.getPurchasePrice().doubleValue());
                    productFormatDTO.setBarCode(yxStoreProduct.getBarCode());
                    productFormatDTO.setPleased(yxStoreProduct.getCost().doubleValue());
                    productFormatDTO.setSalesReference(yxStoreProduct.getSalesReference());
                    newListFormatDTO.add(productFormatDTO);
                }
                //插入之前清空
                yxStoreProductAttrValueRepository.deleteByProductId(id);
                //保存值
                yxStoreProductAttrValueRepository.saveAll(valueGroup);


                Map<String, Object> map = new LinkedHashMap<>();
                map.put("attr", jsonObject.get("attr"));
                map.put("value", newListFormatDTO);

                //保存结果
                setResult(map, id);
            }

        }

    }

    /**
     * 查询可以参与促销的商品
     *
     * @param criteria
     * @param pageable
     * @return
     */
    @Override
    public Map<String, Object> getPromoteProduct(PromoteProductQueryCriteria criteria, Pageable pageable) {
        //分类标识 空查全部，1：按指定分类查询
        String cateLogo="";
        //根据商品分类ID切换
        List<Integer> listCateId=null;
        if (criteria.getCateId() != null && criteria.getCateId() != -1) {
            //根据商品分类ID查询所有子集ID
            List<Map<String, Integer>> listMap = yxStoreCategoryService.findByChildCategory(criteria.getCateId());
             listCateId =new ArrayList<>();
            for (Map<String, Integer> mapData : listMap) {
                //拼装所有子集的分类ID
                if (mapData.get("id") != null) {

                }
                if (mapData.get("pid") != null) {
                    listCateId.add(mapData.get("pid"));

                }
            }
            cateLogo="1";
        }

        Page<Map> page = yxStoreProductRepository.getPromoteProduct(criteria.getStoreName(),cateLogo, listCateId, criteria.getBeginTime(), criteria.getEndTime(), pageable);
        List<YxStoreProductDTO> listData = new ArrayList<>();
        for (Map mapData : page.getContent()) {

            YxStoreProductDTO dto = new YxStoreProductDTO();
            dto.setId(Integer.parseInt(mapData.get("id").toString()));
            dto.setStoreName(mapData.get("storeName").toString());
            YxStoreCategorySmallDTO storeCategory = new YxStoreCategorySmallDTO();
            storeCategory.setCateName(mapData.get("cateName").toString());
            dto.setStoreCategory(storeCategory);
            if (mapData.get("price") != null) {
                BigDecimal decimal = new BigDecimal(mapData.get("price").toString());
                dto.setPrice(decimal);
            } else {
                dto.setPrice(BigDecimal.ZERO);
            }
            listData.add(dto);
        }
        Map<String, Object> map = new LinkedHashMap<>(2);
        map.put("content", listData);
        map.put("totalElements", page.getTotalElements());
        return map;
    }
    /**
     * 查询商品表中的品牌
     * @return
     */
    @Override
    public List<String> getListBrandName() {
        return yxStoreProductRepository.getListBrandName();
    }
}